#--coding:utf-8--
# cython: language_level=3
import numpy as np
import time
import os
import pickle
from enum import Enum, auto  
import datetime
from datetime import timezone
from datetime import timedelta


SECOND_1900_TO_1970 = 2208988800

def parse_GPS_time():  
    '''解析一包数据的GPS时间
    '''
    dataTimeNow = datetime.datetime.now()
    strDataTimePackage = dataTimeNow.astimezone(timezone(timedelta(hours=-0))).strftime("%Y-%m-%d %H:%M:%S")
    # 转换成时间数组
    timeArray = time.strptime(strDataTimePackage, "%Y-%m-%d %H:%M:%S")
    # 转换成时间戳
    unix_t = time.mktime(timeArray)
    unix_t = str(unix_t).split('.')[0]
    unix_t = int(unix_t) + SECOND_1900_TO_1970
    return unix_t, dataTimeNow.microsecond


class Event_Continue_Info(object):
    """初始化事件连续帧的参数
    """
    def __init__(self, start_forward_time=0, timenow=0, coincidence=0):
        # self.start_time=time.time() -start_forward_time                #出现、开始时间
        self.start_time = timenow - start_forward_time  # 出现、开始时间
        self.end_time = self.start_time  # 最新、结束时间
        parse_time = list(parse_GPS_time())
        parse_time[0] = parse_time[0] - start_forward_time
        self.format_start_time = parse_time  # 开始时间的格式化形式
        self.format_end_time = self.format_start_time  # 最新时间的格式化形式
        self.hit_count = 1  # 连续帧出现次数
        self.event_no = -1  # 事件编号
        self.longitude = 0  # 经度
        self.latitude = 0  # 纬度
        self.pc_id = 0
        self.global_frame_time = self.start_time
        self.global_frame_id = 0
        self.eventInfoList = []


class Abnormal_Class_Index(object):
        """事件/场景对应编号
        """
        congestion=1 
        breakdown = 2

class Pc_Info_Index(Enum):
    """枚举点云输入信息对应的索引
    """
    frameNo = auto()  # 帧号 0
    targetId = auto()  # 毫米波雷达id 1
    angle = auto()  # 航向角 2
    laneNo = auto()  # 车道号 3
    latitude = auto()  # 纬度 4
    longitude = auto()  # 经度 5
    xAcceleration = auto()  #  x加速度6
    xCoordinate = auto()  # x位置 7
    xVelocity = auto()  # x速度 8
    yAcceleration = auto()  # y加速度 9
    yCoordinate = auto()  # y位置 10
    yVelocity = auto()  # y速度 11
    timestamp = auto() #时间戳 12

class Detect_Class_Type(object):
    """点云检测结果的分类id
    """
    # 融合感知软件输出类别
    non_motor_type = [1,3]
    motor_type = [0, 2, 5, 6, 7, 8]
    all = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 54]
    target_type = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 54]
    big_car = [2, 5, 6, 7]
    car = [0]
    bicycle = [1]
    bus = [2,8]
    motorcycle = [54]
    people = [4]
    largetruck = [5, 7]
    truck = [5, 6, 7]
    none_type = [54]
    minibus = [8]
    littletruck = [54]
    non_people = [0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 54]
    spill = [11]
    roadwork = [9, 10]  

class Mean_V_Info(object):
    """平均速度对应信息,输出为km/h
    """
    default_mean_v = 255

    def __init__(self, max_v):
        """max_v:km/h
        """
        self.__max_v = max_v
        self.sum_v = 0
        self.sum_num = 0
        self.mean_v = max_v
        self.cur_num = 0  ###linxiao 0524
        self.cur_target_length = 0  ###linxiao 0529
        self.cur_occupancy = 0  ###linxiao 0529
        self.cur_mean_v = 255  ###linxiao 0529
        self.statistice_congestion_count = {1: 0, 2: 0, 3: 0, 4: 0}
        self.statistice_congestion = Congestion_Level.unblocked
        self.congestion = Congestion_Level.unblocked

    def update(self, v):
        """v:m/s,减少一点*3.6的计算量,放到需要计算平均速度时*3.6
        """
        self.sum_v += v
        self.sum_num += 1

    def get_mean_v(self):
        """输出km/h
        """
        self.mean_v = Mean_V_Info.default_mean_v if self.sum_num == 0 else self.sum_v * 3.6 / self.sum_num

    def clear(self):
        self.sum_v = 0
        self.sum_num = 0
        self.statistice_congestion_count = {1: 0, 2: 0, 3: 0, 4: 0}
        # self.mean_v=self.__max_v #为了发送给平台,不对mean_v清零,而在每次判断道路拥堵时更新mean_v


class Detect_Info(object):
    '''目标的感知信息
    '''
    def __init__(self):
        self.l, self.w, self.h = None,None,None
        self.src = None
        self.angle = None
        self.class_id = None
        self.coincidence = None
        self.v = None 
        self.pc_id = None
        self.longitude = None
        self.latitude = None
        self.cur_id_time = None
        self.cur_global_frameid = None
        self.origin_id = None
        self.orgcode = None

    def fill_data(self, origin_data):
        frameNo,targetNum,targetId,angle,laneNo,latitude,longitude,xAcceleration,xCoordinate,xVelocity,yAcceleration,yCoordinate,yVelocity,timestamp,IP = origin_data
        IP_dict = {132:11, 136:12, 197:13, 113:14, 254:15, 116:16, 140:17, 144:18}    
        self.l, self.w, self.h = 0, 0, 0
        self.src = 1
        self.angle = angle
        self.class_id = targetId
        self.coincidence = 0
        self.v = np.sqrt(xVelocity ** 2 + yVelocity ** 2) # v/3.6
        self.pc_id = IP_dict[IP] # pc_id  # 基站编号
        self.longitude = longitude
        self.latitude = latitude
        self.cur_id_time = timestamp
        self.cur_global_frameid = frameNo
        self.origin_id = targetId
        self.orgcode = 0
        self.IP = IP


class Station_Info(object):
    '''单基站的感知信息
    '''
    def __init__(self):
        self.station_no = None
        self.participant_num =None
        self.station_participant_id = []
        self.participants_speed = []
        self.average_speed = None
        self.average_density = None
        self.cur_global_frameid = None
        self.longitude,self.latitude = None, None
        self.vehicle_nums = 0

    def fill_data(self, origin_data):
        frameNo,targetNum,targetId,angle,laneNo,latitude,longitude,xAcceleration,xCoordinate,xVelocity,yAcceleration,yCoordinate,yVelocity,timestamp,IP = origin_data
        # IP_dict = {'10.143.187.132':11, '10.143.187.136':12, '10.151.98.197':13, '10.151.106.113':14, '10.151.98.254':15, '10.151.106.116':16,'10.143.187.140':17, '10.143.187.144':18}
        IP_dict = {132:11, 136:12, 197:13, 113:14, 254:15, 116:16,140:17, 144:18}
        self.station_no = IP_dict[IP]
        self.participant_num = targetNum
        self.station_participant_id.append(targetId)
        self.participants_speed.append(np.sqrt(xVelocity ** 2 + yVelocity ** 2))
        self.cur_global_frameid = frameNo
        self.longitude , self.latitude = longitude,latitude
class Congestion_Level(Enum):
    """拥堵程度索引"""
    unblocked = 1  # 畅通
    slightly_congested = auto()  # 轻度拥堵
    moderately_congested = auto()  # 中度拥堵
    seriously_congested = auto()  # 严重拥堵

class History_Info(object):
    '''目标历史信息初始化
    '''
    def __init__(self):
        self.t, self.x, self.y, self.v = [], [], [], []
        self.cal_speed = []
        self.moving_average_speed = []
        self.acceleration = []
        self.moving_average_after_cal = []
        self.speeding_count = 0
        self.unspeeding_count = 0  ####linxiao 0702
        self.stroll_count = 0
        self.speeding_rate = 0
        self.stroll_rate = 0
        self.x_diff = []
        # self.t_diff = []
        self.car_l = []
        # self.x_diff_mean = 0
        self.x_min = 0
        self.x_max = 0
        self.normal_count = 0
        self.normal_rate = 0
        # self.mean_v = None
        self.px = []
        self.py = []

class Traffic_Flow_Radar(object):
    '''定义异常事件检测逻辑过程及输出函数，须调用进行事件检测功能
    '''
    def __init__(self):
        """初始化
        """
        global eventDetectOffFlag
        eventDetectOffFlag = False
        self.new_time = [] #初始化判定时间
        self.history_events = {}
        self.pc_num = 1 
        self.event_cnt = 1

        self._init_total_info()

        self._init_abnormal_event_continue_info()

        self._init_history_abnormal_event()

    def _event_no_switch(self,old_event_no):
        '''事件编号转换 18激光雷达,28毫米波雷达
        '''
        new_event_no =int('28'+str(old_event_no))
        return new_event_no

    def use(self, raw_input_info, statistics_flag,timestamp_now):
        """
        @param:
        input_info感知信息
        statistics_flag:是否进行统计信息
        """
        input_info = raw_input_info              
        if eventDetectOffFlag:
            input_info = np.zeros((0,62))
            return 0
            
        t_start_use = time.time()

        if input_info.shape[0] == 0:
            self.cur_time = time.time()
            boxnum = 0
        else:
            self.new_time.append(timestamp_now)
            self.cur_time = timestamp_now


        """获取计算统计量和异常事件检测的预备信息"""
        self.get_pre_info(input_info) 

        """异常事件检测"""
        self.detect_abnormal_event(statistics_flag)  #事件检测


    def _init_history_abnormal_event(self):
        """初始化历史异常事件  id:[info]
        """
        self.history_congestion = {} 
        self.history_all_event_output_for_B5 = {}
        self.not_confirm_event_for_B5 = {} #用于事件输出的缓存功能

    def _init_abnormal_event_continue_info(self):
        """初始化异常事件的连续出现
        """
        self.station_id_continue_congestion = {} 

    def detect_abnormal_event(self, del_flag):
        """异常事件检测
        @param:
            del_flag:是否清除过久的历史记录
        """
        self.del_flag = del_flag
        t_now = time.time()
        self._init_abnormal_event_info()
        """拥堵事件检测"""
        self._detect_congestion()  
        self._judge_congestion()   

    def _init_abnormal_event_info(self):
        """初始化异常事件检测的信息
        """
        self.cur_congestion = [] #高风险交互冲突

    def _detect_congestion(self):
        unhit_congestion = set(self.station_id_continue_congestion.keys())
        for station_id in self.cur_station_info.keys():
            if self.cur_station_info[station_id].average_speed != None and self.cur_station_info[station_id].average_density != None:
                if self.cur_station_info[station_id].average_speed < 8.3 and self.cur_station_info[station_id].average_density > 20:
                    self.update_now_and_history(station_id,self.station_id_continue_congestion,self.history_congestion,unhit_congestion)
        for station_id in unhit_congestion:
            self.station_id_continue_congestion.pop(station_id)    

    def _judge_congestion(self):
        for station_id,info in self.station_id_continue_congestion.items():
            if info.hit_count < 10:
                continue
            self.cur_congestion.append(station_id)
            
    def _del_long_time_miss_history(self, history_event):
        """删除太长时间未出现的历史记录"""
        long_time_miss_idxs = set(history_event.keys())
        for idx in history_event:
            if self.cur_time - history_event[idx][-1].end_time <= 10:
                long_time_miss_idxs.remove(idx)
        for idx in long_time_miss_idxs:  # 超过10s
            history_event.pop(idx)

    def _del_long_time_miss_history_high_risk_interact(self, id_continue_high_risk_interact):
        """删除太长时间未出现的id_continue历史记录"""
        long_time_miss_idxs = set(id_continue_high_risk_interact.keys())
        for idx in id_continue_high_risk_interact:
            if self.cur_time - id_continue_high_risk_interact[idx].global_frame_time <= 10:
                long_time_miss_idxs.remove(idx)
        for idx in long_time_miss_idxs:  # 超过10s
            id_continue_high_risk_interact.pop(idx)

    def update_now_and_history(self, station_id, station_id_continue_info, history_event, unhit_station_idxs,
                               start_forward_time=0):
        """更新最新事件连续出现的帧数和时间段，并保存历史时间段中
        """
        if station_id not in station_id_continue_info:
            station_id_continue_info[station_id] = Event_Continue_Info(start_forward_time, self.cur_time)
            this_idx_continue_info = station_id_continue_info[station_id]
            this_idx_continue_info.pc_id = self.cur_station_info[station_id].station_no
            this_idx_continue_info.global_frame_id = self.cur_station_info[station_id].cur_global_frameid
            this_idx_continue_info.longitude = self.cur_station_info[station_id].longitude
            this_idx_continue_info.latitude = self.cur_station_info[station_id].latitude           

            # 添加到历史事件中
            if station_id not in history_event:
                self.event_cnt += 1
                self.event_cnt = self.event_cnt % 1000000  #将事件编码控制在1000000以内
                this_idx_continue_info.event_no = self.event_cnt
                history_event[station_id] = [this_idx_continue_info]
            else:
                this_history_event = history_event[station_id]
                if this_idx_continue_info.start_time - this_history_event[-1].end_time <= 30:  # 30s内同一idx检测出同一类型事件
                    this_history_event[-1].end_time = this_idx_continue_info.end_time

                    this_idx_continue_info.event_no = this_history_event[-1].event_no  #沿用事件编号
                else:
                    self.event_cnt += 1
                    self.event_cnt = self.event_cnt % 1000000
                    this_idx_continue_info.event_no = self.event_cnt
                    history_event[station_id] = [this_idx_continue_info]  # 只记录最新的  之前是append保存历史的所有记录(耗内存)
        else:
            if station_id in unhit_station_idxs:
                unhit_station_idxs.remove(station_id)  # 移除当前帧出现的上一帧出现的目标
                this_idx_continue_info = station_id_continue_info[station_id]
                this_idx_continue_info.hit_count += 1
                this_idx_continue_info.end_time = self.cur_time

                if station_id not in history_event:  # 超时被删
                    self.event_cnt += 1
                    self.event_cnt = self.event_cnt % 1000000
                    this_idx_continue_info.event_no = self.event_cnt
                    history_event[station_id] = [this_idx_continue_info]
                else:
                    # 更新历史事件
                    history_event[station_id][-1].end_time = this_idx_continue_info.end_time


        if self.del_flag:  # 删除超时的历史记录,每帧调用太耗时
            self._del_long_time_miss_history(history_event)

    def get_pre_info(self, input_info):
        """获取计算统计量和异常事件检测的预备信息"""
        t_now = time.time()
        # self._own_frame_id+=1
        self._init_cur_info()       #"""初始化当前帧信息"""
        self._get_cur_id_info(input_info)       # """获取当前检测信息"""


    def _init_total_info(self):
        """初始化时间段里的统计量"""
        self.total_statistics = {}  # 当前时间段的统计信息:车流量、时间占有率
        self.last_id_info = []  # 保存上一阵的id对应信息，用于计算bmp下的速度
        self.id_count = {}  # 记录当前id出现次数
        # need to clear
        self.history_speed_info = {}  # linxiao_0514

    def _init_cur_info(self):
        """初始化当前帧信息"""
        self.cur_id_info = {}  # 当前帧id对应的检测信息
        self.cur_station_info = {} #单基站当前的检测信息
        self.cur_statistics = {}  # 当前帧的瞬时信息:排队长度、空间占有率、车头间距、车头时距


    def _get_cur_id_info(self, input_info):
        """获取当前检测信息"""

        id_index = Pc_Info_Index.targetId.value
        IP_dict = {132:11, 136:12, 197:13, 113:14, 254:15, 116:16, 140:17, 144:18}  
        for i in range(11,19):
            self.cur_station_info[i] = Station_Info()
        for this_info in zip(input_info):
            self.cur_id_info[this_info[0][id_index]] = Detect_Info()
            self.cur_id_info[this_info[0][id_index]].fill_data(this_info[0])
            # self.cur_station_info[IP_dict[this_info[0][14]]] = Station_Info()
            self.cur_station_info[IP_dict[this_info[0][14]]].fill_data(this_info[0])
        for i in self.cur_station_info.keys():
            if self.cur_station_info[i].participant_num != None:
                self.cur_station_info[i].average_speed = sum(self.cur_station_info[i].participants_speed)/len(self.cur_station_info[i].station_participant_id)
                self.cur_station_info[i].average_density = self.cur_station_info[i].participant_num / (self.cur_station_info[i].average_speed*0.1)
                self.cur_station_info[i].vehicle_nums = len(self.cur_station_info[i].station_participant_id)
    def _save_info(self, output_path, info):
        """将变量保存成文件
        """
        file_info = open(output_path, 'wb')
        pickle.dump(info, file_info)
        file_info.close()

    def _load_info(self, data_path):
        """将文件变为变量
        """
        file_info = open(data_path, 'rb')
        return pickle.load(file_info)

    def _init_new_output_event_number(self, lane_config_path):
        '''根据记录文件加载初始的事件编号
        '''
        if os.path.exists(lane_config_path + 'new_event_number.pkl'):
            new_event_no = self._load_info(lane_config_path + 'new_event_number.pkl') + 1000
        else:
            new_event_no = 0
        return new_event_no
    
    def judge_station_direction(self,station_id):
        up_direction = [15,16,17,18]
        down_direction = [11,12,13,14]
        if station_id in up_direction:
            return 0
        else:
            return 1
        
    def switch_output_for_B5(self,output):
        result =[]
        for event in output:
            IP_dict = {132:11, 136:12, 197:13, 113:14, 254:15, 116:16, 140:17, 144:18}  
            station_orgCode = {11:"ZW1", 12:"ZW2", 13:"HW1", 14:"HW6", 15:"HW3", 16:"HW7", 17:"ZW3" , 18:"ZW4", 1:"TLS_3_1", 2:"TLS_3_2", 3:"TLS_4_1", 4:"TLS_4_2", 5:"TLS_1_1", 6:"TLS_1_2", 7:"TLS_2_1", 8:"TLS_2_2"}
            stake = {"ZW1":"K1660+950", "ZW2":"K1660+100", "HW1":"K1664+320", "HW6":"K1649+770", "HW3":"K1664+275", "HW7":"K1649+740", "ZW3":"K1660+980", "ZW4":"K1660+130", "TLS_3_1":"K1656+837", "TLS_3_2":"K1655+155", "TLS_4_1":"K1653+460", "TLS_4_2":"K1651+756", "TLS_1_1":"K1651+749", "TLS_1_2":"K1653+549", "TLS_2_1":"K1655+154", "TLS_2_2":"K1656+840"}
            UporgCode = {11:"HW1", 12:"ZW1", 13:"HW1", 14:"TLS_4_2", 15:"ZW3", 16:"HW7", 17:"ZW4" , 18:"TLS_2_2", 1:"ZW2", 2:"TLS_3_1", 3:"TLS_3_2", 4:"TLS_4_1", 5:"HW7", 6:"TLS_1_1", 7:"TLS_1_2", 8:"TLS_2_1"}
            downorgCode = {11:"ZW1", 12:"ZW2", 13:"ZW1", 14:"HW6", 15:"HW3", 16:"TLS_1_1", 17:"ZW3" , 18:"ZW4", 1:"TLS_3_1", 2:"TLS_3_2", 3:"TLS_4_1", 4:"TLS_4_2", 5:"TLS_1_1", 6:"TLS_1_2", 7:"TLS_2_1", 8:"TLS_2_2"}
            lon_lat = {
                "HW1":[106.90458785, 30.33287997],
                "ZW1":[106.9291, 30.31261],
                "ZW2":[106.93471, 30.30665],
                "HW6":[107.01842, 30.25336],
                "TLS_4_2":[107.0000207, 30.2608549],
                "HW3":[106.9048189, 30.3325609],
                "ZW3":[106.92912, 30.31298],
                "HW7":[107.01873, 30.2534],
                "TLS_1_1":[107.0009195, 30.2606119],
                "ZW4":[106.93473, 30.30705],
                "TLS_1_2":[106.9882976, 30.2712984],
                "TLS_3_1":[106.9622785, 30.2931042],
                "TLS_3_2":[106.9752273, 30.2819368],
                "TLS_2_1":[106.9752964, 30.2823442],
                "TLS_2_2":[106.962415, 30.2934835],
                "TLS_4_1":[106.9881101, 30.2710593],
            }
            congestion = {
                1:"畅通",
                2:"轻度拥堵",
                3:"中度拥堵",
                4:"严重拥堵",
            }
            event_dict = {}
            dt_object = datetime.datetime.fromtimestamp(event[0])
            formatted_time = dt_object.strftime('%Y-%m-%d %H:%M:%S')
            # event_dict["timestamp"] = formatted_time
            # event_dict["direction"] =str(event[1])
            # event_dict["sLon"] = event[2]
            # event_dict["sLat"] = event[3]
            # event_dict["eLat"] = event[4]
            # event_dict["eLat"] = event[5]
            # event_dict["secLevel"] = str(event[6])
            # event_dict["isBreakdown"] = event[7]
            # event_dict["eventId"] = event[8]
            # event_dict["eventInfo"] = event[9]
            
            event_dict["orgCode"] = downorgCode[event[10]]
            event_dict["upOrgCode"] =UporgCode[event[10]]
            event_dict["intervalSpeed"] = event[11]
            event_dict["totalFlow"] = event[12]
            event_dict["congestion"] = congestion[event[6]]
            event_dict["globalTime"] = formatted_time
            event_dict["secLevel"] = event[6]
            event_dict["lastTimeIndex"] = 1
            event_dict["info"] = ""
            event_dict["updateTime"] = formatted_time
            event_dict["timestamp"] = formatted_time
            event_dict["direction"] = event[1]
            event_dict["sNum"] = stake[UporgCode[event[10]]]
            event_dict["eNum"] = stake[downorgCode[event[10]]]
            event_dict["sLon"] = lon_lat[UporgCode[event[10]]][0]
            event_dict["sLat"] = lon_lat[UporgCode[event[10]]][1]
            event_dict["eLon"] = lon_lat[downorgCode[event[10]]][0]
            event_dict["eLat"] = lon_lat[downorgCode[event[10]]][1]
            event_dict["isBreakdown"] = event[7]
            event_dict["eventId"] = event[8]
            event_dict["eventInfo"] = event[9]
            result.append(event_dict)
        return result
        
    def get_event_output_for_B5(self):
        """获取B5帧所需的信息"""
        self.all_event_output_for_B5 = []
        self.confirmed_event_for_B5 = []
        self.has_new_event = False
        #高风险交互冲突的类型列表
                    
        def judge_new_event(cur_event, history_infos):
            for id in cur_event:
                this_history_info = history_infos[id][-1]
                event_num = this_history_info.event_no 
                if event_num not in self.history_events.keys():
                    self.has_new_event = True
                    self.history_events[event_num] = this_history_info.end_time
                    self.history_all_event_output_for_B5[event_num] = [this_history_info.end_time, []]
                else:
                    #最新的事件记录结束时间-上一次出现的结束时间>=30s则判定也有新事件发生
                    if this_history_info.end_time - self.history_events[event_num] >= 30:
                        self.has_new_event = True
                        self.history_events[event_num] = this_history_info.end_time
                        self.history_all_event_output_for_B5[event_num] = [this_history_info.end_time, []]

            #若事件结束时间超过300s则删除时间历史记录
            for his_event in list(self.history_events.keys()):
                if self.cur_time - self.history_events[his_event] > 300:
                    self.history_events.pop(his_event)
          
        def one_event_info_for_B5(cur_event, history_infos, abnormal_class_index):
            B5_event = []
            #若judge_new_event后判定有新事件发生，则 self.all_event_output_for_B5.extend(B5_event)
            if self.has_new_event:         
                for station_id in cur_event:                           
                    if station_id not in history_infos.keys():
                        continue
                    this_history_info = history_infos[station_id][-1] 
                    B5_event.append([this_history_info.end_time,
                                     self.judge_station_direction(this_history_info.pc_id),
                                     this_history_info.longitude,
                                     this_history_info.latitude,
                                     this_history_info.longitude,
                                     this_history_info.latitude,
                                     4, # 拥堵等级 4-严重拥堵
                                     0, # 是否阻断,0-否
                                    #  this_history_info.event_no, #事件编号
                                     this_history_info.event_no,
                                     "",
                                     this_history_info.pc_id,
                                     self.cur_station_info[this_history_info.pc_id].average_speed,
                                     self.cur_station_info[this_history_info.pc_id].participant_num]
                                    )

            if len(B5_event) != 0:                
                self.all_event_output_for_B5.extend(B5_event)


        
        #########################################################判断是否有新的异常事件发生######################################################
        # judge_new_event_high_risk_interact(self.cur_high_risk_interact,self.history_high_risk_interact) 
        judge_new_event(self.cur_congestion,self.history_congestion)


        #########################################################输出异常事件检测结果#############################################################
        # one_event_info_for_B5(self.cur_high_risk_interact,self.history_high_risk_interact,Abnormal_Class_Index.high_risk_interact)
        one_event_info_for_B5(self.cur_congestion,self.history_congestion,Abnormal_Class_Index.congestion)
    
    def get_B5(self):
        '''获取异常事件检测结果B5
        '''       
        if eventDetectOffFlag:
            # B5 = [0, 0, 0, 0, len(self.all_event_output_for_B5), 0, self.all_event_output_for_B5, 0]
            B5 = [0, 0, 0, 0, 1, 0, [[42036, 13, 1, 2, 2, 1, [[100119776.0, 1.0, 0.6900000000000001, 3, [[0, 120.6196439, 31.4262607, 0.0, 0.0, 0.0, 0.0, 1, 3.0, 1662016801.2086966, 1662016801.2086966, 1662016801.2086966, 15512.0, 1662016801.2086966], [1, 120.6195647, 31.4262861, 0.0, 0.0, 0.0, 0.0, 1, 3.0, 1662016802.1787002, 1662016802.1787002, 1662016802.1787002, 15519.0, 1662016802.1787002], [2, 120.6194563, 31.4264929, 0.0, 0.0, 0.0, 0.0, 1, 2.0, 1662016805.6129925, 1662016805.6129925, 1662016805.6129925, 15547.0, 1662016805.6129925]], [5.01, 2.7999999999999994, 1.72]]], 120.6195647, 31.4262861, 1662016802.1787002, 1662016805.6129925]], 0]
            return B5
        self.get_event_output_for_B5()
     
        for event in self.all_event_output_for_B5:
            if event[8] in self.history_all_event_output_for_B5:
                self.history_all_event_output_for_B5[event[8]][1] = event #hisroy[事件编号]=[end_time,[编号，类型，方位，车道，目标个数，id列表，开始时间，结束时间]]
        
        for event_no in list(self.history_all_event_output_for_B5.keys()):
            if self.cur_time - self.history_all_event_output_for_B5[event_no][0] > 7:
                if len(self.history_all_event_output_for_B5[event_no]) != 0:
                    self.history_all_event_output_for_B5[event_no][1][0] = self.cur_time
                    self.all_event_output_for_B5.append(self.history_all_event_output_for_B5[event_no][1])
                del self.history_all_event_output_for_B5[event_no]

        B5 = self.all_event_output_for_B5
        if B5 != None:
            if len(B5):
                final_result = self.switch_output_for_B5(B5)
                # print(B5)
                return final_result

     
# if __name__ == "__main__":
#     import copy
#     np.random.seed(122504)
#     COLORS = np.random.randint(0, 255, size=(500, 3), dtype="uint8")

#     B0_time = time.time()
#     B1_time = time.time()
#     B2_time = time.time()
#     B3_time = time.time()
#     B4_time = time.time()
#     B5_time = time.time()
#     B0_flag = False
#     B1_flag = False
#     B2_flag = False
#     B3_flag = False
#     B4_flag = False
#     B5_flag = False

#     ii = 1
#     last_cur_time = 0

#     lidar_topic_ip = ['10.143.187.149', '10.143.187.153', '10.143.187.157', '10.143.187.161', '10.143.187.165', '10.143.187.168', '10.143.187.171', '10.143.187.174']
#     radar_topic_ip = ['10.143.187.132', '10.143.187.136', '10.143.187.140', '10.143.187.131', '10.143.187.144']

#     #逐帧读取融合感知数据，并调用traffic_flow.get_B5()进行异常事件检测
#     for pointtime in [[0, 65535 ,'1001']]: 
#         if ii > 0:
#             traffic_flow = Traffic_Flow_Radar(r'/data/tongluoshan/config/', 1) #配置文件路径 基站个数  
#         ii += 1
#         firstFrame = False
#         for frame_i in range(pointtime[0], pointtime[1]):
#             try:
#                 df = pd.read_csv("/data/tongluoshan/output_radar/%d.csv"%frame_i)
#                 lidar_info = df.to_numpy()
#                 # lidar_info = np.load("/data/data_npy/data_0402/%d.npy"%frame_i,allow_pickle=True)
#                 if len(lidar_info) == 2 and len(lidar_info[1]) <= 12:
#                     if lidar_info[0].shape[0] == 0:continue
#                 else:
#                     if lidar_info.shape[0] == 0:continue
#             except:
#                 continue
            
#             if len(lidar_info[0])==14:
#                 date_format = '%Y-%m-%d %H:%M:%S:%f'
#                 timestamp_now = lidar_info[0][13]
#                 t_B4_now = timestamp_now
#                 t_B3_now = timestamp_now
#                 if timestamp_now - last_cur_time <0.05:
#                     continue
#                 else:
#                     last_cur_time = timestamp_now
#                 timeArray = time.localtime(t_B4_now)  # 秒数
#                 otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
#                 if not firstFrame:
#                     t_B4 = lidar_info[0][13]
#                     t_B3 = lidar_info[0][13]
#                 firstFrame = True                

#             # 模拟定时发送
#             t_now = time.time()
#             if t_now - B0_time >= 0.1:  # 10Hz
#                 B0_flag = True
#                 B0_time = t_now
#             else:
#                 B0_flag = False
#             if t_now - B1_time >= 60:  # 1/60Hz
#                 B1_flag = True
#                 B1_time = t_now
#             else:
#                 B1_flag = False
#             if t_now - B2_time >= 0.1:  # 10Hz
#                 B2_flag = True
#                 B2_time = t_now
#             else:
#                 B2_flag = False
#             if t_B3_now - t_B3 >= 1:  # 1Hz
#                 B3_flag = True
#                 t_B3 = t_B3_now
#             else:
#                 B3_flag = False
#             if t_B4_now - t_B4 >= 60:  # 1/60Hz
#                 B4_flag = True
#                 t_B4 = t_B4_now
#             else:
#                 B4_flag = False
#             if t_now - B5_time >= 5:  # 0.2Hz
#                 B5_flag = True
#                 B5_time = t_now
#             else:
#                 B5_flag = False

#             t_1 = time.time()
#             # 进行统计统计量  B1与B4应该同频率紅綠燈相位
#             if B4_flag:  
#                 traffic_flow.use(lidar_info, True,timestamp_now)
#             else:
#                 traffic_flow.use(lidar_info, False,timestamp_now)
            
#             b0, b1, b2, b3, b4, b5 = 0, 0, 0, 0, 0, 0

#             b5 = traffic_flow.get_B5()



